package org.raymond.iworks.core.utils;

//import com.alibaba.excel.EasyExcel;
//import com.alibaba.excel.read.listener.PageReadListener;
//import com.alibaba.excel.support.ExcelTypeEnum;
//import com.alibaba.fastjson.JSON;

public class ExcelUtil {
    private static final String DOWNLOAD_PATH = "../docs/excel/downloads";
    private static final String UPLOAD_PATH = "../docs/excel/uploads";

    private ExcelUtil(){}

    /*
    public static ExcelTypeEnum extractExcelType(String filename){
        if(StringUtils.isBlank(filename)){
            throw new BaseException(ErrorCode.BAD_REQUEST, String.format("filename must not be null"));
        }
        String suffix = StringUtils.substring(filename, StringUtils.indexOf(filename, ".")+1);
        ExcelTypeEnum excelType = null;
        if(StringUtils.equalsIgnoreCase(suffix, "XLSX")){
            excelType = ExcelTypeEnum.XLSX;
        }
        if(StringUtils.equalsIgnoreCase(suffix, "XLS")){
            excelType = ExcelTypeEnum.XLS;
        }
        if(StringUtils.equalsIgnoreCase(suffix, "CSV")){
            excelType = ExcelTypeEnum.CSV;
        }
        if(null == excelType){
            throw new BaseException(ErrorCode.UPLOAD_FAILED, String.format("file type[%s] not support", excelType));
        }
        return excelType;
    }

    public static <T> void read(String filename, byte[] content, Class<T> clazz, Consumer<List<T>> consumer){
        ExcelTypeEnum excelTypeEnum = extractExcelType(filename);
        InputStream is = new ByteArrayInputStream(content);
        EasyExcel.read(is, clazz, new PageReadListener<T>(consumer)).excelType(excelTypeEnum).sheet().doRead();
    }

    public static <T> void write(HttpServletResponse response, Class<T> clazz, List<T> list, String sheet) throws IOException {
        try{
            if(CollectionUtil.isEmpty(list)){
                throw new IOException(ErrorCode.NOT_FOUND.getMessage());
            }
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''"+sheet+".xls");
            response.setContentType(ContentType.FILE_CONTENT_TYPE.get("xls"));
            response.setCharacterEncoding("utf-8");
            EasyExcel.write(response.getOutputStream(), clazz).autoCloseStream(Boolean.FALSE).sheet(sheet).doWrite(list);
        }catch(IOException e){
            response.reset();
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");
            response.getWriter().write(JSON.toJSONString(Result.error(ErrorCode.DOWNLOAD_FAILED.getCode(), ErrorUtil.getErrorLog(e))));
        }
    }*/
}
